package handler

import (
	"fmt"
	"net/http"

	"github.com/emicklei/go-restful"
	log "github.com/golang/glog"
	"k8s.io/api/core/v1"
)

type APIHandler struct {
}

type NamespaceList struct {
	Namespaces []v1.Namespace `json:"Namespaces"`
}
type Man struct {
	Id, Name string
}

// CreateHTTPAPIHandler creates the restful Container and defines the routes the API will serve
func CreateHTTPAPIHandler() (http.Handler, error) {
	apiHandler := APIHandler{}

	wsContainer := restful.NewContainer()

	wsContainer.EnableContentEncoding(true)

	cors := restful.CrossOriginResourceSharing{
		AllowedHeaders: []string{"Content-Type", "Accept"},
		AllowedMethods: []string{"GET", "POST", "PUT", "DELETE"},
		CookiesAllowed: true,
		Container:      wsContainer,
	}
	wsContainer.Filter(cors.Filter)
	wsContainer.Filter(wsContainer.OPTIONSFilter)

	apiV1Ws := new(restful.WebService)

	apiV1Ws.Path("/tfjobs/api").
		Consumes(restful.MIME_XML, restful.MIME_JSON).
		Produces(restful.MIME_JSON, restful.MIME_XML)

	apiV1Ws.Route(
		apiV1Ws.GET("/namespace/{user-id}").
			To(apiHandler.handleGetNamespaces).
			Writes(NamespaceList{}))

	apiV1Ws.Route(
		apiV1Ws.POST("/users").To(apiHandler.updateMan))

	wsContainer.Add(apiV1Ws)
	return wsContainer, nil
}

func (apiHandler *APIHandler) handleGetNamespaces(request *restful.Request, response *restful.Response) {
	var l NamespaceList
	id := request.PathParameter("user-id")
	fmt.Println(id)
	log.Infof("successfully listed namespaces")
	if err := response.WriteHeaderAndEntity(http.StatusOK, l); err != nil {
		log.Errorf("Failed to write response: %v", err)
	}
}

func (apiHandler *APIHandler) updateMan(request *restful.Request, response *restful.Response) {
	usr := new(Man)
	err := request.ReadEntity(&usr)
	// here you would update the user with some persistence system
	if err == nil {
		response.WriteEntity(usr)
	} else {
		response.WriteError(http.StatusInternalServerError, err)
	}
}
